package com.army.filemanage.service.impl;

import com.army.filemanage.databean.FileCriteria;
import com.army.filemanage.databean.StandardResponse;
import com.army.filemanage.service.FileService;
import com.army.filemanage.utils.IdUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Value("${project.root.path}")
    private String rootPath = "rootPath";
    @Value("${project.baseUrl}")
    private String baseUrl;

    @Override
    public StandardResponse uploadFile(FileCriteria criteria) {
        String filePath = this.saveFile(criteria);
        String imgPath = baseUrl + "filePath/" + filePath;

        StandardResponse standardResponse = new StandardResponse();
        standardResponse.setSuccess(true);
        standardResponse.setStatusCode("100");
        standardResponse.setStatusDesc("上传成功");
        standardResponse.setData(imgPath);
        return standardResponse;
    }

    @Override
    public String saveFile(FileCriteria criteria) {
        log.info("上传文件开始!");
        String pictureId = IdUtils.getId("FP");
        String fileName = pictureId + "." + criteria.getFileExtension();
        criteria.setFileName(fileName);


        String filePath = sourceFile(criteria);
        log.info("File Path: " + filePath);
        log.info("上传文件结束!");
        return filePath;
    }

    private String sourceFile(FileCriteria criteria) {
        byte[] attachmentFileByteArray = criteria.getFileByteArray();
        if (null != attachmentFileByteArray) {

            log.info("1.1.创建根目录.");
            String basePath = rootPath + this.genDatePath();
            File basePathFolder = new File(basePath);
            if (!basePathFolder.exists()) basePathFolder.mkdirs();
            log.info("根目录: " + basePath);

            File file = new File(basePath + File.separator + criteria.getFileName());
            log.info("1.2.保存源文件 - 绝对路径: " + file.getAbsolutePath());

            try {
                FileCopyUtils.copy(attachmentFileByteArray, file);
                log.info("1.3.1.保存源文件 - 保存成功 !!!");

                String relativePath = this.genDatePath() + File.separator + criteria.getFileName();

                return relativePath;
            } catch (IOException e) {
                log.info("1.3.2.保存源文件 - 保存失败 !!!");
                file.deleteOnExit();
                return "";
            }
        }
        return "";
    }

    private String genDatePath(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String yyyyMMdd = sdf.format(new Date());

        return yyyyMMdd;
    }
}
